package com.xh.bussiness.teachbook.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.teachbook.dao.TeachingBookPlanDetailMapper;
import com.xh.bussiness.teachbook.model.TeachingBookPlanDetail;
import com.xh.bussiness.teachbook.service.ITeachingBookPlanDetailService;
import com.xh.core.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;


@Service
public class TeachingBookPlanDetailServiceImpl extends BaseServiceImpl<TeachingBookPlanDetailMapper,TeachingBookPlanDetail> implements ITeachingBookPlanDetailService {


    @Override
    public Integer queryOrderNoByParentId(String parentId) {
        QueryWrapper<TeachingBookPlanDetail> qw = new QueryWrapper<>();
        qw.eq("parent_id", parentId);
        qw.orderByDesc("order_no");
        List<TeachingBookPlanDetail> teachingBookPlanDetails =
                this.dao.selectList(qw);
        if (!CollectionUtils.isEmpty(teachingBookPlanDetails)) {
            return teachingBookPlanDetails.get(0).getOrderNo() == null ? 1 : teachingBookPlanDetails.get(0).getOrderNo();
        }
        return 1;
    }

    @Override
    public void teachingBookPlanDetailUpOrDown(String sourceId, String targetId, Integer sourceNo, Integer targetNo, Integer operateType) {

    }

    @Override
    public void initOrderNo() {
        QueryWrapper<TeachingBookPlanDetail> qw1 = new QueryWrapper<>();
        qw1.eq("parent_id","0");
        qw1.orderByAsc("create_time");
        List<TeachingBookPlanDetail> teachingBookPlanDetails = this.dao.selectList(qw1);
        for (int i = 0; i < teachingBookPlanDetails.size(); i++) {
            TeachingBookPlanDetail teachingBookPlanDetail = teachingBookPlanDetails.get(i);
            teachingBookPlanDetail.setOrderNo((i + 1));

            QueryWrapper<TeachingBookPlanDetail> qw2 = new QueryWrapper<>();
            qw2.eq("parent_id", teachingBookPlanDetail.getId());
            List<TeachingBookPlanDetail> childs = this.dao.selectList(qw2);
            if (!CollectionUtils.isEmpty(childs)) {
                for (int j = 0; j < childs.size(); j++) {
                    TeachingBookPlanDetail child = childs.get(j);
                    child.setOrderNo((j + 1));
                    this.update(child);
                }
            }
            this.update(teachingBookPlanDetail);
        }
    }
}
